package com.example.lots_of_demo.security;

import com.example.lots_of_demo.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : LZJ
 * @description : code for LZJ
 * @date : 2021/2/13
 */
@Slf4j
@Component("myRestfulAccessDeniedHandler")
public class MyRestfulAccessDeniedHandler implements AccessDeniedHandler {

    @Value("${jwt.tokenKeyName}")
    private String tokenKeyName;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JWTUtils jwtUtils;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        String userName = jwtUtils.getUserNameFromToken(request.getHeader(tokenKeyName).substring(tokenHead.length()));
        log.info("用户为<<{}>>访问<<{}>>尝试无权限访问", userName, request.getRequestURI());
        response.setStatus(401);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().append("{\"code\":0,\"msg\":\"无权限访问!\",\"data\":\"success\"}");
    }
}
